package com.gridmobi.xrtb.hooks;

import com.gridmobi.xrtb.common.ExecutorPool;
import com.gridmobi.xrtb.dspcounter.DspCounterJob;
import com.gridmobi.xrtb.handler.monitor.RtbStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * @author huangyongchao
 * 注册优雅停机事件 暂时不能捕获kill -9 所以尽量避免Kill -9
 * <p>
 * 上报内存数据等操作
 */
@Component
public class ShutdownHookEvent {
    private static final Logger logger = LoggerFactory.getLogger(ShutdownHookEvent.class);

    @Autowired
    DspCounterJob dspCounterJob;

    @PreDestroy
    public void exeWhenShutdown() throws Exception {
        /*
        释放资源锁
         */
        RtbStatus.RELEASE_LOCK.set(true);
        dspCounterJob.sendClicks();
        /*上报报表*/
        logger.info("***********************System Is     Shuting*******************************");
        logger.info("***********************System Is     Sleep 10s ****************************");
        logger.info("***********************Don`t  Force  Kill***********************************");

        Thread.sleep(10 * 1000);
        /*
         *等待线程池任务队列执行完毕
         */

        ExecutorPool.getExecutor().shutdown();

        if (!ExecutorPool.getExecutor().awaitTermination(1, TimeUnit.MINUTES)) {
            ExecutorPool.getExecutor().shutdownNow();
        }

        logger.info("***********************System    Shutdown*******************************");

    }
}
